<template>
  <el-dialog v-model="showUserDialog" title="绑定部门信息" @close="clearText">
    <el-form ref="refPersonForm" :model="personForm"  :rules="verifyRules">
      <div class="personInfo">
        <div style="text-align: center;margin-bottom: 20px">
          <el-image :src="personForm.avatarUrl" style="width: 100px;height: 100px;border-radius: 50px;" lazy>
            <template #error>
              <img src="/static/avatar.png" style="width: 100px;height: 100px;border-radius: 50px;" >
            </template>
            <template #placeholder>
              <img src="/static/avatar.png" style="width: 100px;height: 100px;border-radius: 50px;" >
            </template>
          </el-image>
        </div>
        <el-form-item prop="sex" label="性&emsp;别">
          <el-select v-model="personForm.sex" class="m-2" placeholder="性别" style="width: 100%">
            <el-option
                v-for="item in sexOptions"
                :key="item.value"
                :label="item.label"
                :value="item.value"/>
          </el-select>
        </el-form-item>
        <el-form-item prop="userphone" label="座机号">
          <el-input
              ref="userphone"
              v-model="personForm.userphone"
              placeholder="座机"
              name="userphone"
              type="text"
              clearable
              auto-complete="on"></el-input>
        </el-form-item>
        <el-form-item prop="departmentId" label="部&emsp;门">
          <el-tree-select v-model="personForm.departmentId"
                          :data="deptTree"
                          :props="defaultProps"
                          check-strictly
                          :render-after-expand="false"
                          placeholder="请选择部门" style="width: 100%" />
        </el-form-item>
        <el-form-item prop="orderNum" label="排&emsp;序">
          <el-input-number v-model="personForm.orderNum" :min="0" :max="1000" style="width: 100%"/>
        </el-form-item>
      </div>
      <el-button :loading="loading" type="primary" style="width:100%;margin-top:20px;"
                 @click.prevent="handleBind(refPersonForm)">确&emsp;定</el-button>
    </el-form>
  </el-dialog>
</template>

<script lang="ts">
import {useConfigStore} from "@/store/config";
import {storeToRefs} from "pinia";
import {onMounted, reactive, ref} from "vue";
import {IUser} from "@/iwb/IUser";
import {FormInstance, FormRules} from "element-plus";
import {validContactNumber} from "@/utils/validate";
import {IDept} from "@/iwb/IConfig";
import {getDepartment} from "@/api/config";
import {useUserStore} from "@/store/user";
import {useRouter} from "vue-router";

export default {
  name: "User",
  setup() {
    const router = useRouter();
    const loading = ref(false);
    const configStore = useConfigStore()
    const {showUserDialog} = storeToRefs(configStore);
    const personForm = ref({} as IUser);
    const refPersonForm = ref<FormInstance>();

    const validateContact = (rule: any, value: string, callback: any) => {
      if (!validContactNumber(value) || value.length !== 11) {
        callback(new Error('请输入正确的座机号'))
      }  else {
        callback();
      }
    };

    const verifyRules = reactive<FormRules>({
      sex: [{required: true, trigger: 'blur', message: '请选择性别'}],
      userphone: [{required: true, trigger: 'blur', validator: validateContact}],
      departmentId: [{required: true, trigger: 'blur', message: '请选择部门'}],
      orderNum: [{required: true, trigger: 'blur', message: '请设置排序'}]
    })

    const defaultProps = ref({
      children: 'children',
      label: 'name',
      value: 'id'
    })
    const sexOptions = ref([{value: 0, label: '男'},{value: 1, label: '女'}]);
    const deptTree = ref([] as Array<IDept>);
    const rolesOptions = ref([{value: "ROLE_USER,ROLE_ADMIN", label:'管理员'}, {value: 'ROLE_USER', label: '普通用户'}])

    const reloadDeptTree = () => {
      loading.value = true;
      getDepartment().then(res => {
        deptTree.value = res.data;
        loading.value = false;
      }).catch(error => {
        console.error(error);
        loading.value = false;
      })
    }

    const handleBind = (formEl: FormInstance | undefined) => {
      if (!formEl) return;
      const userStore = useUserStore();
      formEl.validate((valid: boolean, fields) => {
        loading.value = true;
        userStore.bindUserDept(personForm.value).then(() => {
          loading.value = true;
          configStore.setHowUserDialog(false);
          router.push({path: '/'});
        }).catch(error=> {
          loading.value = false;
          console.error(error);
        });
      });
    }

    const clearText = () => {
      personForm.value = {} as IUser;
      personForm.value.sex = 0;
      personForm.value.orderNum = 0;
    }

    onMounted(() => {
      personForm.value.sex = 0;
      personForm.value.orderNum = 0;
      reloadDeptTree();
    })

    return {
      loading,
      showUserDialog,
      personForm,
      refPersonForm,
      verifyRules,
      defaultProps,
      sexOptions,
      deptTree,
      rolesOptions,
      handleBind,
      clearText
    }
  }
}
</script>

<style scoped lang="scss">
.personInfo {
  margin: 0 10px 10px 10px;
}

.personForm {
  display: grid;
  gap: 20px;
  grid-template-columns: 1fr 1fr;

  .left .right {
    width: 100%;
  }
  :deep(.personForm) {
    .el-select {
      width: 100%;
    }
  }
}

.dialog-footer button:first-child {
  margin-right: 10px;
}
</style>